<template>
    <div>
        <section class="content-header">排班管理&nbsp;/&nbsp;值班安排&nbsp;/&nbsp;排班安排</section>
        <section class="select-body clearfix">
            <div class="col-md-1 clearfix">
                <div class="form-group clearfix">
                    <select
                        class="form-control select2"
                        style="width: 100%;"
                        v-model="zhibanList.year"
                        @change="selectWeek"
                    >
                        <option value="2018">2018年</option>
                        <option value="2017">2017年</option>
                        <option value="2016">2016年</option>
                    </select>
                </div>
            </div>
            <div class="col-md-1 clearfix">
                <div class="form-group clearfix">
                    <select
                        class="form-control select2"
                        style="width: 100%;"
                        v-model="zhibanList.month"
                        @change="selectWeek"
                    >
                        <option value="1" selected>01月</option>
                        <option value="2">02月</option>
                        <option value="3">03月</option>
                        <option value="4">04月</option>
                        <option value="5">05月</option>
                        <option value="6">06月</option>
                        <option value="7">07月</option>
                        <option value="8">08月</option>
                        <option value="9">09月</option>
                        <option value="10">10月</option>
                        <option value="11">11月</option>
                        <option value="12">12月</option>
                    </select>
                </div>
            </div>
            <div class="col-md-1 clearfix">
                <div class="form-group clearfix">
                    <select
                        class="form-control select2"
                        style="width: 100%;"
                        v-model="zhibanList.week"
                        @change="selectWeek"
                    >
                        <option value="1" selected>第一周</option>
                        <option value="2">第二周</option>
                        <option value="3">第三周</option>
                        <option value="4">第四周</option>
                        <option value="5" :class="{show:isShow}">第五周</option>
                    </select>
                </div>
            </div>
            <div class="col-md-1 col-md-offset-8 clearfix">
                <button type="button" class="btn btn-primary" @click="signMuban">
                    <i class="fa fa-sign-in" aria-hidden="true"></i> 导入模板
                </button>
            </div>
        </section>
        <section class="main clearfix">
            <div class="box">
                <div class="box-body">
                    <table
                        id="example"
                        class="table table-bordered table-hover"
                        style="font-size:14px"
                    >
                        <thead style="font-weight:700">
                            <tr>
                                <td></td>
                                <td
                                    v-for="(item,index) in week"
                                    :key="item.value"
                                >{{item}}&nbsp;&nbsp;&nbsp;&nbsp;{{weekend[index]}}</td>
                            </tr>
                        </thead>
                        <tbody ref="xxx">
                            <tr v-if="timeList.length==0">
                                <td colspan="999">暂无数据</td>
                            </tr>
                            <tr v-for="(item,index1) in timeList" :key="item.value">
                                <td style="vertical-align: middle">{{item.time1}}-{{item.time2}}</td>
                                <td
                                    class="maxTd"
                                    :class="{'stopMove':item.schedualCycle.cycleList[index2]==0}"
                                    v-for="(i,index2) in week"
                                    :key="i.value"
                                    @drop="drop($event, item, index1,index2)"
                                    @dragover="allowDrop($event,index2,item.schedualCycle.cycleList)"
                                >
                                    <!-- <div class="select-item" v-for="(people,index3) in paibanList.timeList[index1].dayList[index2].personList" :key="people.value">
                                        <i data-v-7fca9cb0="" aria-hidden="true" class="fa fa-user"></i>{{people.name}}{{index3}}
                                        <i class="fa fa-fw fa-times" @click="removePeople(index1,index2,index3)"></i>
                                    </div>-->
                                    <div
                                        class="select-item"
                                        v-for="(people,index3) in timeList[index1].dayList[index2].personList"
                                        :key="people.value"
                                    >
                                        <i data-v-7fca9cb0 aria-hidden="true" class="fa fa-user"></i>
                                        {{people.name}}
                                        <i
                                            class="fa fa-fw fa-times"
                                            @click="removePeople(index1,index2,index3)"
                                        ></i>
                                    </div>
                                </td>
                            </tr>
                        </tbody>
                    </table>
                </div>
            </div>
        </section>
        <section class="person clearfix">
            <p>值班人员列表</p>
            <div class="col-md-12 clearfix">
                <div class="col-md-3 clearfix">
                    <danwei v-model="zhibanList.companyId"/>
                </div>
                <div class="col-md-3 clearfix">
                    <bumen v-model="zhibanList.deptId" :companyId="zhibanList.companyId"/>
                </div>
                <div class="col-md-3 clearfix">
                    <gangwei
                        v-model="zhibanList.jobName"
                        :companyId="zhibanList.companyId"
                        :deptId="zhibanList.deptId"
                    />
                </div>
                <div class="col-md-3 clearfix">
                    <button
                        type="button"
                        class="btn btn-primary"
                        style="float:left"
                        @click="getZhibanList()"
                    >确定</button>
                </div>
            </div>
            <div class="col-md-12 clearfix">
                <ul class="user">
                    <li
                        v-for="item in peopleList"
                        :key="item.value"
                        draggable="true"
                        @dragstart="drag($event)"
                    >
                        <i class="fa fa-user" aria-hidden="true"></i>
                        {{item.name}}
                    </li>
                </ul>
            </div>
        </section>
        <section class="clearfix" style="margin-top:20px;padding-bottom:20px">
            <div class="col-md-6 col-md-offset-1" style="text-align: center;">
                <button
                    type="button"
                    class="btn btn-default"
                    style="float:left;background:#fff"
                    @click="saveMuban"
                >保存为模板</button>
                <button type="button" class="btn btn-primary" @click="see">提交</button>
                <button
                    type="button"
                    class="btn btn-default"
                    style="float:right;background:#fff"
                    @click="goback"
                >取消</button>
            </div>
        </section>
    </div>
</template>

<script>
import bumen from "@/components/common/scheduling/bumen.vue";
import danwei from "@/components/common/scheduling/danwei.vue";
import gangwei from "@/components/common/scheduling/gangwei.vue";

import { getItemName } from "@/filters/index.js";

export default {
    data() {
        return {
            peopleList: [],
            timeList: [],

            week: [],
            weekend: [
                "星期一",
                "星期二",
                "星期三",
                "星期四",
                "星期五",
                "星期六",
                "星期日"
            ],
            isShow: true,
            zhibanList: {
                jobName: "",
                deptId: "",
                companyId: "",
                year: this.getYear().getFullYear(),
                month: this.getYear().getMonth() + 1,
                week: "1"
            },
            paibanList: {
                timeList: []
            },
            text: ""
        };
    },
    components: {
        bumen,
        danwei,
        gangwei
    },
    mounted() {
        this.selectWeek();
    },
    methods: {
        // 保存模板
        saveMuban() {
            localStorage.setItem("timeList", JSON.stringify(this.timeList));
            this.$$message({
                message: "保存模板成功",
                type: "success"
            });
        },

        // 导入模板
        signMuban() {
            this.timeList = JSON.parse(localStorage.getItem("timeList"));
            this.$$message({
                message: "导入模板成功",
                type: "success"
            });
            // console.log(JSON.parse(localStorage.getItem('timeList')))
        },
        //拖拽效果
        drag: function(event) {
            // console.log('drag')
            event.dataTransfer.setData(
                "text",
                "<item>" + event.target.innerHTML
            );
            this.text = event.target.innerText;
        },
        drop: function(event, item, index1, index2) {
            // event.preventDefault()
            // console.log('drop')

            var text = event.dataTransfer.getData("text");
            var cellIndex = event.target.cellIndex - 1;
            var personName = "";
            var chongfu = false;
            //如果text以<item>开头
            if (text.indexOf("<item>") == 0 && event.target.nodeName == "TD") {
                // personName = this.text.replace(/\s+/g, "")
                personName = this.text;
                this.timeList[index1].dayList[index2].planId = item.planId;
                this.timeList[index1].dayList[index2].timeId = item.timeId;
                this.timeList[index1].dayList[
                    index2
                ].year = this.zhibanList.year;
                this.timeList[index1].dayList[
                    index2
                ].month = this.zhibanList.month;
                this.timeList[index1].dayList[
                    index2
                ].week = this.zhibanList.week;
                this.timeList[index1].dayList[index2].daytime = this.week[
                    index2
                ];
                this.timeList[index1].dayList[index2].personList.forEach(
                    (element, index) => {
                        if (element.name == personName) {
                            chongfu = true;
                            this.$$message({
                                message: "请勿重复添加！",
                                type: "error"
                            });
                        }
                    }
                );
                if (!!!chongfu) {
                    this.timeList[index1].dayList[index2].personList.push({
                        name: personName,
                        value: getItemName(
                            personName.replace(/(^\s*)|(\s*$)/g, ""),
                            this.peopleList,
                            "name",
                            "value"
                        )
                        // value: '11'
                    });
                }
            }
        },
        allowDrop: function(event, index2, item) {
            // console.log(item,index2)
            if (item[index2] == 1) {
                event.preventDefault();
            }
        },

        //当前是几几年
        getYear() {
            var date = new Date();
            var year = date.getFullYear();
            return date;
        },

        //得到当前年月的第几周
        getWeek(year, month, week) {
            // console.log(this.getWeeks(year, month))
            if (this.getWeeks(year, month) == 5) {
                this.isShow = false;
                // console.log(this.isShow)
            }
            if (this.getWeeks(year, month) == 4) {
                this.isShow = true;
                // console.log(this.isShow)
            }
            var monthDay = new Date(year, month, 0).getDate();
            var d = new Date();
            // what day is first day
            d.setFullYear(year, month - 1, 1);
            var w1 = d.getDay();
            if (w1 == 0) w1 = 7;
            // total day of month
            d.setFullYear(year, month, 0);
            var dd = d.getDate();
            var d1 = 0;
            // first Monday
            if (w1 != 1) {
                d1 = 7 - w1 + 2;
            } else {
                d1 = 1;
            }
            var week_count = Math.ceil((dd - d1 + 1) / 7);
            var arr = [];
            for (var i = 0; i < week_count; i++) {
                var weekData = [];
                var monday = d1 + i * 7;
                var sunday = monday + 6;

                for (var j = 0; j < 6; j++) {
                    monday = d1 + i * 7;
                    monday += j;
                    if (monday <= monthDay) {
                        if (month < 10) {
                            if (monday < 10) {
                                var from =
                                    year +
                                    "年0" +
                                    month +
                                    "月0" +
                                    monday +
                                    "日";
                            } else {
                                var from =
                                    year + "年0" + month + "月" + monday + "日";
                            }
                        } else {
                            if (monday < 10) {
                                var from =
                                    year + "年" + month + "月0" + monday + "日";
                            } else {
                                var from =
                                    year + "年" + month + "月" + monday + "日";
                            }
                        }
                        weekData.push(from);
                    }
                }
                var to;
                if (sunday <= dd) {
                    if (month < 10) {
                        if (sunday < 10) {
                            to = year + "年0" + month + "月0" + sunday + "日";
                        } else {
                            to = year + "年0" + month + "月" + sunday + "日";
                        }
                    } else {
                        if (sunday < 10) {
                            to = year + "年" + month + "月0" + sunday + "日";
                        } else {
                            to = year + "年" + month + "月" + sunday + "日";
                        }
                    }

                    weekData.push(to);
                } else {
                    var day2 = [];
                    d.setFullYear(year, month - 1, sunday);
                    for (var k = 1; k <= d.getDate(); k++) {
                        if (d.getMonth() + 1 < 10) {
                            if (k < 10) {
                                day2.push(
                                    d.getFullYear() +
                                        "年0" +
                                        (d.getMonth() + 1) +
                                        "月0" +
                                        k +
                                        "日"
                                );
                            } else {
                                day2.push(
                                    d.getFullYear() +
                                        "年0" +
                                        (d.getMonth() + 1) +
                                        "月" +
                                        k +
                                        "日"
                                );
                            }
                        } else {
                            if (k < 10) {
                                day2.push(
                                    d.getFullYear() +
                                        "年" +
                                        (d.getMonth() + 1) +
                                        "月0" +
                                        k +
                                        "日"
                                );
                            } else {
                                day2.push(
                                    d.getFullYear() +
                                        "年" +
                                        (d.getMonth() + 1) +
                                        "月" +
                                        k +
                                        "日"
                                );
                            }
                        }
                    }
                    // to = d.getFullYear() + "年" + (d.getMonth() + 1) + "月" + d.getDate() + "日";
                    for (var key in day2) {
                        weekData.push(day2[key]);
                    }
                }
                arr.push(weekData);
            }
            // console.log(arr[week - 1]);
            this.week = arr[week - 1];
        },
        selectWeek() {
            this.getWeek(
                this.zhibanList.year,
                this.zhibanList.month,
                this.zhibanList.week
            );
            this.getZhibanList();
        },
        getWeeks(year, month) {
            var d = new Date();
            // 该月第一天
            d.setFullYear(year, month - 1, 1);
            var w1 = d.getDay();
            if (w1 == 0) w1 = 7;
            // 该月天数
            d.setFullYear(year, month, 0);
            var dd = d.getDate();
            // 第一个周一
            let d1;
            if (w1 != 1) d1 = 7 - w1 + 2;
            else d1 = 1;
            let week_count = Math.ceil((dd - d1 + 1) / 7);
            return week_count;
        },

        //得到值班列表
        getZhibanList() {
            // console.log(this.zhibanList)
            this.$api.paiban.timeList(this.zhibanList).then(res => {
                if (res.success) {
                    // console.log(res);
                    this.peopleList = res.data.personList;
                    this.timeList = res.data.timeList;
                    for (let i in this.timeList) {
                        if (this.timeList[i].dayList.length == 0) {
                            for (let j in this.week) {
                                this.timeList[i].dayList.push({
                                    personList: [],
                                    planId: this.timeList[i].planId,
                                    timeId: this.timeList[i].timeId,
                                    time1: this.timeList[i].time1,
                                    time2: this.timeList[i].time2,
                                    year: this.zhibanList.year,
                                    month: this.zhibanList.month,
                                    day: "",
                                    week: this.zhibanList.week,
                                    daytime: this.week[j]
                                });
                            }
                        }
                    }
                    console.log(this.timeList);
                }
            });
        },

        //删除值班人员
        removePeople(index1, index2, index3) {
            this.timeList[index1].dayList[index2].personList.splice(index3, 1);
            this.$$message({
                message: "删除成功！",
                type: "success"
            });
        },

        //提交值班列表
        see() {
            let stop = true;
            for (
                let i = 0;
                i <
                $(this.$refs.xxx)
                    .find("td")
                    .not(".stopMove").length;
                i++
            ) {
                if (
                    $(this.$refs.xxx)
                        .find("td")
                        .not(".stopMove")[i].innerText == ""
                ) {
                    stop = false;
                }
            }
            if (!!stop) {
                // console.log('OK')
                this.$api.paiban
                    .newDayUrgent({
                        timeList: this.timeList
                    })
                    .then(res => {
                        if (res.success) {
                            this.$$message({
                                message: "安排成功！",
                                type: "success"
                            });
                            this.$router.push({ path: "/scheduling/duty" });
                            // console.log(res)
                        }
                    });
            } else {
                this.$$message({
                    message: "请重新进行值班安排！",
                    type: "error"
                });
            }
        },
        //取消排班操作
        goback() {
            this.$router.push({ path: "/scheduling/duty" });
        }
    }
};
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
.nav-tabs {
    li {
        a {
            padding: 10px 40px;
        }
    }
}
.form-group {
    margin-bottom: 5px;
}
.person {
    background: #fff;
    margin: 0 10px;
    border: 1px solid #bbb;
    padding: 10px 20px;
    p {
        border-bottom: 1px solid #bbb;
        padding: 5px;
    }
    .user {
        margin-top: 20px;
        li {
            list-style: none;
            float: left;
            padding: 5px 40px;
            width: 150px;
            cursor: pointer;
        }
    }
}
.show {
    display: none !important;
}
.stopMove {
    background: #f5f5f5;
}
.maxTd {
    max-width: 500px;
    min-width: 100px;
}
</style>
<style>
.select-item {
    background-color: #5bc0de;
    display: inline-block;
    text-align: center;
    border-radius: 3px;
    margin-right: 10px;
    cursor: pointer;
    padding: 6px 10px;
    color: #000;
    margin-bottom: 5px;
}
</style>
